package com.b2mining.integration.controllers;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import org.apache.log4j.Logger;
import com.b2mining.daemons.TXTFile;
import com.b2mining.daemons.TXTReader;
import com.b2mining.integration.beans.Retention;
import com.b2mining.integration.beans.RetentionContainer;
import com.b2mining.integration.client.txt.RetentionTXTMapper;
import com.b2mining.integration.helper.Constantes;
import com.b2mining.integration.helper.EnviarMail;

public class TXTRetentionController {
	 public Logger log = Logger.getLogger(this.getClass());
	 SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyyMMdd-HHmmssSSS");
	   int bandaviso=0;
	   
	   //nuevo metodo para Retenciones
	    public int enviarRetencionSend(TXTFile txtFile){
	   	 int flagenviarRetentionSend=0;
	   	 RetentionContainer  lstRetentionsOK= new RetentionContainer();
			 
			 try{
				 	RetentionTXTMapper  txtMapper = new RetentionTXTMapper ();
				 	//>>>>>>>>>>>>>>> chekar aki
		            lstRetentionsOK=(RetentionContainer)txtMapper.parseTXT(txtFile.getFileReader());
		            log.debug("cantidad de retenciones leidas procesadas correctamente antes de enviar: " + lstRetentionsOK.getBeanCount());
		            for(int i=0; i<lstRetentionsOK.getBeanCount();i++)
		            {
		            	log.debug("cantidad de items leidos por Retencion " + ((Retention)lstRetentionsOK.getBean(i)).getNumRetencion() +": "+ ((Retention)lstRetentionsOK.getBean(i)).getItemCount());
		            }
		            flagenviarRetentionSend=2;
		        }
		        catch(Exception e){
		            log.fatal("Exception en enviarRetentionSend: " + e,e);
		            flagenviarRetentionSend=3;
		        }
		        finally{
			        if(flagenviarRetentionSend==3 && bandaviso==0){
			        	RetentionTXTMapper midt=new RetentionTXTMapper();
			       		// enviar correo
			   	        String subject = Constantes.SUBJECTCABECERAEMPRESA1+ midt.getMiEmpresaBuscada()+"-"+Constantes.SUBJECTERRORRETREADER;
			   	        String messages = Constantes.CUERPOERRORRETREADER+TXTReader.varnombre+" para "+midt.getMiEmpresaBuscada();
			   	        
			   	        for(int asd=0;asd<midt.getListaErrorTXT().size();asd++)
			   	        {
			   	        	messages=messages+"\n"+midt.getListaErrorTXT().get(asd).toString();
			   	        }
			   	        log.debug("Subject: "+subject+" - messages: "+messages);
			   	        EnviarMail.enviandoMailError(subject,messages,txtFile.getCodigoAccion(),TXTReader.varnombre);
			   	        flagenviarRetentionSend=1;
			        }
			        	log.debug("flagenviarInvoiceSend: "+ flagenviarRetentionSend);	
		        }
		        
				return flagenviarRetentionSend;  
	   }
	 
	 public String construirCabecera(TXTFile txtFile){ 
	        String action=txtFile.getCodigoAccion();
	        String orgId=agregarCaracter(txtFile.getOrgId(),30);
	        String orgUserId=agregarCaracter(txtFile.getOrgUserId(),12);
	        String errorCode=Constantes.NOERRORPROCESS;
	        String header=action+orgId+orgUserId+errorCode;
	        log.debug("header: " + header);
	        return header;
	    }
	 
	 public String agregarCaracter(String palabra,int cantidad){
	        String frase = "";
	        if(palabra!=null){
	                frase = palabra.trim();
	        }
	        if(frase.length()>cantidad){
	                frase=frase.substring(0,cantidad);
	        }
	        while (frase.length()<cantidad){
	                frase = frase + " ";
	        }

	        return frase;
	    }
	 
	 public String crearArchivo(String ruta, String header, String body){
	        try{
	            Writer output = null;
	            File file = new File(ruta);
	            output = new BufferedWriter(new FileWriter(file));
	            output.write(header);
	            output.write(body);
	            output.close();
	            log.debug("Creo el archivo txt: " + ruta);	
	            return ruta;
	        }
	        catch(Exception e){
	            log.error("Exception e: " +e);
	            return null;
	        }
	    }
	 
}
